package cn.humaohua.study.hadoop.cmdrunner.c5;

import cn.humaohua.study.hadoop.cmdrunner.Test;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.StringUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Arrays;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

@Component
public class WritableTest implements Test {
    IntWritable writable = new IntWritable(163);

    @Override
    public void test() throws Exception {
        byte[] bytes = serialize(writable);
        System.out.println("bytes=" + Arrays.toString(bytes));//bytes=[0, 0, 0, -93]//-93+256=163

        //断言字节数组的长度为4
        assertThat(bytes.length, is(4));
//        assertThat(bytes.length, greaterThanOrEqualTo(4));
        assertThat(StringUtils.byteToHexString(bytes), is("000000a3"));//0f000000a3=163

        IntWritable intWritable = new IntWritable();
        deserialize(intWritable, bytes);
        assertThat(intWritable.get(), is(163));
        System.out.println("intWritable=" + intWritable.get());//intWritable=163
    }

    public static byte[] serialize(Writable writable) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream dataOut = new DataOutputStream(out);
        writable.write(dataOut);
        dataOut.close();
        return out.toByteArray();
    }

    public static byte[] deserialize(Writable writable, byte[] bytes) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        DataInputStream dataIn = new DataInputStream(in);
        writable.readFields(dataIn);
        dataIn.close();
        return bytes;
    }
}
